package com.jiuyin.dianjing.api.enums;

import android.net.ParseException;

import com.google.gson.JsonParseException;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.api.exception.DataResultException;
import com.jiuyin.dianjing.util.ToastUtil;

import org.json.JSONException;

import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;

import retrofit2.HttpException;

/**
 * @author Administrator
 */

public enum ExceptionReason {
    /**
     * 接口错误类型
     */
    CONNECT_ERROR,
    CONNECT_TIMEOUT,
    BAD_NETWORK,
    PARSE_ERROR,
    CANCEL_BY_USER,
    UNKNOWN_ERROR;

    public static void onDealError(Throwable e) {
        if (e instanceof HttpException) {
            onException(BAD_NETWORK);
        } else if (e instanceof ConnectException
                || e instanceof UnknownHostException) {
            onException(CONNECT_ERROR);
        } else if (e instanceof InterruptedIOException) {
            onException(CONNECT_TIMEOUT);
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            onException(PARSE_ERROR);
        } else if (e.getMessage().contains(CANCEL_BY_USER.name())) {
            onException(CANCEL_BY_USER);
        } else if (e instanceof DataResultException) {
            ToastUtil.showLong(e.getMessage());
        } else {
            onException(UNKNOWN_ERROR);
        }
    }

    /**
     * 请求异常
     *
     * @param reason ExceptionReason
     */
    public static void onException(ExceptionReason reason) {
        switch (reason) {
            case CONNECT_ERROR:
                ToastUtil.showLong(R.string.connect_error);
                break;
            case CONNECT_TIMEOUT:
                ToastUtil.showLong(R.string.connect_timeout);
                break;
            case BAD_NETWORK:
                ToastUtil.showLong(R.string.bad_network);
                break;
            case PARSE_ERROR:
                ToastUtil.showLong(R.string.parse_error);
                break;
            case CANCEL_BY_USER:
                ToastUtil.showLong(R.string.cancel_by_user);
                break;
            case UNKNOWN_ERROR:
            default:
                ToastUtil.showLong(R.string.unknown_error);
                break;
        }
    }
}